package io.github.junxworks.qt.modules.tushare.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

import io.github.junxworks.qt.modules.tushare.entity.DStockTradeDailyBasic;
import io.github.junxworks.qt.modules.tushare.mapper.TradeInfoMapper;
import io.github.junxworks.qt.modules.tushare.service.TradeInfoService;
import io.github.junxworks.qt.modules.tushare.service.TushareService;
import jakarta.annotation.PostConstruct;

@Service
public class TradeInfoServiceImpl extends TushareService implements TradeInfoService {

	private BiMap<String, Integer> calCache = HashBiMap.create(3000);

	@Autowired
	private TradeInfoMapper tradeInfoMapper;

	@PostConstruct
	public void init() {
		refreshTradeCal();
	}

	public void refreshTradeCal() {
		calCache.clear();
		List<String> tradeCal = tradeInfoMapper.selectAllTradeDate();
		for (int i = 0, len = tradeCal.size(); i < len; i++) {
			calCache.put(tradeCal.get(i), i);
		}
	}

	@Override
	public boolean isWeekend(String tradeDate) {
		return !calCache.containsKey(tradeDate);
	}

	@Override
	public String queryTradeCalByOffset(String date, int offset) {
		if (!calCache.isEmpty()) {
			int index = calCache.get(date);
			return calCache.inverse().get(index + offset);
		}
		return null;
	}

	@Override
	public DStockTradeDailyBasic queryTradeDailyBasicByCodeAndDate(String tsCode, String tradeDate) {
		return tradeInfoMapper.queryTradeDailyBasicByCodeAndDate(tsCode, tradeDate);
	}

	@Override
	public List<DStockTradeDailyBasic> queryTradeDailyBasicByDate(String tradeDate) {
		return tradeInfoMapper.queryTradeDailyBasicByDate(tradeDate);
	}

	@Override
	public String getTradeDate(int index) {
		return calCache.inverse().get(calCache.size() - index - 1);
	}

	@Override
	public String queryRecentTradeDate(String targetDate) {
		return tradeInfoMapper.queryRecentTradeDate(targetDate);
	}
}
